package com.schoolComments.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author 马园博
 * @date 2023/04/23/15:48
 * @Project hm-dianping
 **/
@Component
public class RedisIdWorker {
    //起始时间  时间戳 = (现在时间 - 起始时间)
    private LocalDateTime startTime = LocalDateTime.of(2001, 2,22,0,0);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成全局唯一id
     * @param keyPrefix redis自增的键
     * @return 生成好的全局唯一id
     */
    public Long getId(String keyPrefix){
        //生成时间戳作为前缀
        //获取现在的时间
        LocalDateTime now = LocalDateTime.now();
        //时间戳
        long timestamp = now.toEpochSecond(ZoneOffset.UTC) - startTime.toEpochSecond(ZoneOffset.UTC);
        //生成自增数作为后缀
        //获取当前日期 用来拼接自增数的键
        String data = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //生成自增数
        Long increment = stringRedisTemplate.opsForValue().increment("increment:" + keyPrefix + ":" + data);

        //拼接返回
        Long ID = timestamp << 32 | increment;
        return ID;
    }



}
